package com.power.sifa.sso;

import cn.dev33.satoken.config.SaSsoConfig;
import cn.dev33.satoken.sso.SaSsoHandle;
import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson2.JSON;
import com.ejlchina.okhttps.OkHttps;
import com.ejlchina.okhttps.internal.SyncHttpTask;
import com.plf.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * SSO Client端 Controller
 */
@RestController
public class SsoClientController {

    @Value("${server.servlet.context-path:#{null}}")
    private String contextpath;

    @Value("${sa-token.sso.editpass-url:#{null}}")
    private String editpassUrl;


    // SSO-Client端：首页
//	@RequestMapping("/status")
    public String status() {
        String str = "<h2>SSO-Client 业务系统应用端 MK3</h2>" +
                "<p>当前会话是否登录：" + StpUtil.isLogin() + "</p>" +
                "<p><a href=\"javascript:location.href='" + contextpath + "/sso/login?back=' + encodeURIComponent(location.href);\">登录</a>" +
                " <a href='" + contextpath + "/sso/logout?back=self'>注销</a></p>";
        return str;
    }

    /*
     * SSO-Client端：处理所有SSO相关请求
     * 		http://{host}:{port}/sso/login			-- Client端登录地址，接受参数：back=登录后的跳转地址
     * 		http://{host}:{port}/sso/logout			-- Client端单点注销地址（isSlo=true时打开），接受参数：back=注销后的跳转地址
     * 		http://{host}:{port}/sso/logoutCall		-- Client端单点注销回调地址（isSlo=true时打开），此接口为框架回调，开发者无需关心
     */
    @RequestMapping("/sso/*")
    public Object ssoRequest() {
        Object re = SaSsoHandle.clientRequest();
        return re;
    }

    // 配置SSO相关参数
    @Autowired
    private void configSso(SaSsoConfig sso) {
        // 配置Http请求处理器
        sso.setSendHttp(url -> {
            System.out.println("发起请求：" + url);
            return OkHttps.sync(url).get().getBody().toString();
        });
    }

    // 全局异常拦截
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        e.printStackTrace();
        return SaResult.error(e.getMessage());
    }

    @RequestMapping("/sso/updatePassword")
    public Map<String, Object> updatePassword(@RequestParam String newPassword) throws BusinessException {

        // 组装url参数
        Object loginId = StpUtil.getLoginId();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = SaFoxUtil.getRandomString(20);
        String sign = SaSsoUtil.getSign(loginId, timestamp, nonce, SaSsoUtil.saSsoTemplate.getSecretkey());

        // 调接口改密码
        SyncHttpTask client=OkHttps.sync(this.editpassUrl);
//        RestUtil.HttpClient client = RestUtil.getClient(this.editpassUrl).post().addInitializer(new TrustAllHttpsInitializer());
        if (null != loginId) {
            client.addBodyPara("loginId", loginId);
        }
        if (StringUtils.hasText(newPassword)) {
            client.addBodyPara("newpass", newPassword);
        }
        if (StringUtils.hasText(timestamp)) {
            client.addBodyPara("timestamp", timestamp);
        }
        if (StringUtils.hasText(nonce)) {
            client.addBodyPara("nonce", nonce);
        }
        if (StringUtils.hasText(timestamp)) {
            client.addBodyPara("sign", sign);
        }
        String resp=client.post().getBody().toString();
        Map<String, Object> back =  JSON.parseObject(resp);
        Integer code = (Integer) back.get("code");
        if (code != 200) {
            throw new BusinessException((String) back.get("msg"));
        }
        return back;

    }

}
